﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web.UI.HtmlControls;
using System.Web.UI;

using DevExpress.Web.ASPxHeadline;

using LMD.Constant;
using LMD.Lib.Controls;
using LMD.Lib.DataClass;

/// <summary>
/// Summary description for Extension
/// </summary>
public static class NewsFeedManager
{
    public const string NEWSFEED_DIV_ID = "divnf";
    public const string HEADLINE_DIV_ID = "divhl";
    public const string COMMENT_COUNT_ID = "divcmc";
    public const string COMMENT_DIV_ID = "divcom";
    public const string COMMENT_FORM_ID = "frcom";
    public const string COMMENT_TXT_ID = "txcom";
    public const string NOTIF_DIV_ID = "divntf";

    public static String BuildNewsFeedList(this NewsFeedData[] arrNF)
    {
        String sxOutput = String.Empty;

        int iLastCustId = 0;
        String sxLastUserId = String.Empty;
        List<NewsFeedData> lsSame = new List<NewsFeedData>();

        for (int i = 0; i < arrNF.Length; i++)
        {
            bool IsSamePoster = false;

            IsSamePoster = !String.IsNullOrEmpty(arrNF[i].sxUserId_Poster) &&
                (arrNF[i].sxUserId_Poster == sxLastUserId);

            IsSamePoster = IsSamePoster || (arrNF[i].iCustomerId > 0 &&
                (arrNF[i].iCustomerId == iLastCustId));

            if(!IsSamePoster)
            {
                if (lsSame.Count == 1)
                {
                    sxOutput += lsSame[0].BuildNewsFeedItem();
                }
                else
                {
                    sxOutput += BuildSimilarNewsFeedGroup(lsSame);
                }
                lsSame.Clear();
            }
            lsSame.Add(arrNF[i]);

            sxLastUserId = arrNF[i].sxUserId_Poster;
            iLastCustId = arrNF[i].iCustomerId;
        }

        if (lsSame.Count == 1)
        {
            sxOutput += lsSame[0].BuildNewsFeedItem();
        }
        else
        {
            sxOutput += BuildSimilarNewsFeedGroup(lsSame);
        }
        lsSame.Clear();

        return sxOutput;
    }

    private static String BuildSimilarNewsFeedGroup(List<NewsFeedData> lsSimilar)
    {
        String sxOutput = String.Empty;

        for (int j = 0; j < lsSimilar.Count; j++)
        {
            if (j == 0)
            {
                sxOutput += lsSimilar[j].BuildNewsFeedItem();
                sxOutput +=
                    String.Format(
                        "<table id=\"tblSimilar_{0}\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\" class=\"nfT\"><tr><td>" +
                        "<a class=\"lnk\" href=\"javascript:showMorePost('{0}');\"> " +
                        "show {1} more similar post{2}</a></td></tr></table>",
                        lsSimilar[j].ID,
                        lsSimilar.Count - 1,
                        lsSimilar.Count > 2 ? "s" : String.Empty);

                sxOutput +=
                    String.Format(
                        "<div id=\"divSimilar_{0}\" style=\"display:none;\">", lsSimilar[j].ID);
            }
            else
            {
                sxOutput += lsSimilar[j].BuildNewsFeedItem();
            }

            if (j == lsSimilar.Count - 1)
            {
                sxOutput += "</div>";
            }
        }
        return sxOutput;
    }

    public static String BuildNewsFeedItem(this NewsFeedData nfData)
    {
        if (nfData.iCustomerId > 0)
        {
            return nfData.BuildNewsFeedItem_PostedByCompany();
        }
        else
        {
            return nfData.BuildNewsFeedItem_PostedByUser();
        }
    }

    public static String BuildNewsFeedItem_PostedByCompany(this NewsFeedData nfData)
    {
        String sxOutput = String.Format(
            "<table cellspacing=\"0\" cellpadding=\"0\" id=\"{1}_{0}\" border=\"0\" class=\"nfT\">" +
                "<tr>" +
                    "<td valign=\"top\" style=\"width:50px;\">" +
                        "<a href=\"CompanyProfile.aspx?cid={2}\"><img src=\"upload/company/{2}.jpg\" alt=\"\" class=\"nfP\" onerror=\"setEmptyCompanyAvatar(this);\" /></a>" +
                    "</td>" +
                    "<td valign=\"bottom\" style=\"padding-left:12px;\">" +
                        "<a class=\"nfH\" href=\"CompanyProfile.aspx?cid={2}\">{3}</a>{12}" +
                        "<div class=\"nfCnt\">{14}{4}{13}</div>" +
                        "<br/>" +
                        "<div class=\"nfD\">{5}{11}</div>" +
                        " &#149; " +
                        "<div class=\"lnk\" onclick=\"OpenComment(this, '{0}');\">" +
                            "<div style=\"display:inline;\" id=\"{10}_{0}\">{6}</div>&nbsp;comment{7}" +
                        "</div>{15}{16}" +
                        "<div id = \"{8}_{0}\" class=\"nfCm\"></div>" +
                        "<div id = \"{9}_{0}\"></div>" +
                    "</td>" +
                "</tr>" +
            "</table>",
            nfData.ID,
            NEWSFEED_DIV_ID,
            nfData.iCustomerId.ToString(),
            nfData.sxCustomerName,
            nfData.sxContent.Replace(KGlobal.NEWSFEED_NEWLINE, "<br/>"),
            nfData.dtmDate.ToString("dd MMM yyyy, HH:mm"),
            nfData.iCommentCount > 0 ? nfData.iCommentCount.ToString() : "be the first to",
            (nfData.iCommentCount > 1) ? "s" : String.Empty,
            COMMENT_DIV_ID,
            COMMENT_FORM_ID,
            COMMENT_COUNT_ID,
            String.IsNullOrEmpty(nfData.sxSourceName) ? String.Empty :
                String.Format(" via <a href=\"{0}\">{1}</a>", nfData.sxSourceURL, nfData.sxSourceName),
            String.IsNullOrEmpty(nfData.sxUserId_Target) ? String.Empty :
                String.Format(
                    "<img src=\"images/arrow-right.png\">&nbsp;<a class=\"nfH\" href=\"NewsFeed.aspx?mode=profile&uid={0}\">{1}</a>",
                    nfData.sxUserId_Target, nfData.sxUserName_Target),
            String.IsNullOrEmpty(nfData.sxUserId_Poster) ? String.Empty :
                String.Format(
                    "<br/>by <a class=\"lnkless\" href=\"NewsFeed.aspx?mode=profile&uid={0}\">{1}</a>",
                    nfData.sxUserId_Poster, nfData.sxUserName_Poster),
            String.IsNullOrEmpty(nfData.sxTitle) ? String.Empty :
                String.Format(
                    "<span class=\"titleFeed\">{0}</span><br>",
                    nfData.sxTitle),
            ICPUser.ID != nfData.sxUserId_Poster ? String.Empty :
                String.Format(" &#149; <div class=\"lnk\" onclick=\"DeleteFeed('{0}');\">delete</div>", nfData.ID),
            String.Format(" &#149; <div class=\"lnk\" onclick=\"BlockFeed_FromCompany('{0}', '{1}_{2}');\">block this customer</div>",
            nfData.iCustomerId.ToString(), NEWSFEED_DIV_ID, nfData.ID)
                );

        return sxOutput;
    }
    public static String BuildNewsFeedItem_PostedByUser(this NewsFeedData nfData)
    {
        String sxOutput = String.Format(
            "<table cellspacing=\"0\" cellpadding=\"0\" id=\"{1}_{0}\" border=\"0\" class=\"nfT\">" +
                "<tr>" +
                    "<td valign=\"top\" style=\"width:50px;\">" +
                        "<a href=\"NewsFeed.aspx?mode=profile&uid={2}\"><img src=\"upload/avatar/{2}.jpg\" alt=\"\" class=\"nfP\" onerror=\"setEmptyUserAvatar(this);\" /></a>" +
                    "</td>" +
                    "<td valign=\"bottom\" style=\"padding-left:12px;\">" +
                        "<a class=\"nfH\" href=\"NewsFeed.aspx?mode=profile&uid={2}\">{3}</a>{12}" +
                        "<div class=\"nfCnt\">{13}{4}</div>" +
                        "<br/>" +
                        "<div class=\"nfD\">{5}{11}</div>" +
                        " &#149; " + 
                        "<div class=\"lnk\" onclick=\"OpenComment(this, '{0}');\">" + 
                            "<div style=\"display:inline;\" id=\"{10}_{0}\">{6}</div>&nbsp;comment{7}" + 
                        "</div>{14}{15}" +
                        "<div id = \"{8}_{0}\" class=\"nfCm\"></div>" +
                        "<div id = \"{9}_{0}\"></div>" +
                    "</td>" +
                "</tr>" +
            "</table>",
            nfData.ID,
            NEWSFEED_DIV_ID,
            nfData.sxUserId_Poster,
            nfData.sxUserName_Poster,
            nfData.sxContent.Replace(KGlobal.NEWSFEED_NEWLINE, "<br/>"),
            nfData.dtmDate.ToString("dd MMM yyyy, HH:mm"),
            nfData.iCommentCount > 0 ? nfData.iCommentCount.ToString() : "be the first to",
            (nfData.iCommentCount > 1) ? "s" : String.Empty,
            COMMENT_DIV_ID,
            COMMENT_FORM_ID,
            COMMENT_COUNT_ID,
            String.IsNullOrEmpty(nfData.sxSourceName) ? String.Empty :
                String.Format(" via <a href=\"{0}\">{1}</a>", nfData.sxSourceURL, nfData.sxSourceName),
            String.IsNullOrEmpty(nfData.sxUserId_Target) ? String.Empty :
                String.Format(
                    "<img src=\"images/arrow-right.png\">&nbsp;<a class=\"nfH\" href=\"NewsFeed.aspx?mode=profile&uid={0}\">{1}</a>", 
                    nfData.sxUserId_Target, nfData.sxUserName_Target),
            String.IsNullOrEmpty(nfData.sxTitle) ? String.Empty :
                String.Format(
                    "<span class=\"titleFeed\">{0}</span><br>",
                    nfData.sxTitle),
            ICPUser.ID != nfData.sxUserId_Poster ? String.Empty :
                String.Format(" &#149; <div class=\"lnk\" onclick=\"DeleteFeed('{0}');\">delete</div>", nfData.ID),
            ICPUser.ID == nfData.sxUserId_Poster ? String.Empty :
                String.Format(" &#149; <div class=\"lnk\" onclick=\"BlockFeed_FromUser('{0}', '{1}_{2}');\">block this user</div>",
                    nfData.sxUserId_Poster, NEWSFEED_DIV_ID, nfData.ID)
                );

        return sxOutput;
    }

    public static String BuildCommentItem(this CommentData cmData)
    {
        String sxOutput = String.Format(
            "<table cellspacing=\"0\" cellpadding=\"0\" id=\"{2}_{1}_{0}\" border=\"0\" class=\"cmT\">" +
                "<tr>" +
                    "<td valign=\"top\" style=\"width:50px;\">" +
                        "<a href=\"NewsFeed.aspx?mode=profile&uid={3}\"><img src=\"upload/avatar/{3}.jpg\" alt=\"\" class=\"cmP\" onerror=\"setEmptyUserAvatar(this);\"/></a>" +
                    "</td>" +
                    "<td valign=\"top\" style=\"padding-left:5px;\">" +
                        "<a href=\"NewsFeed.aspx?mode=profile&uid={3}\" class=\"cmH\">{4}</a>" +
                        "<div class=\"cmCnt\">{5}</div>" +
                        "<br/>" +
                        "<div class=\"cmD\">{6}</div>" +
                    "</td>" +
                "</tr>" +
            "</table>",
            cmData.ID,
            cmData.NewsFeedID,
            COMMENT_DIV_ID,
            cmData.sxUserId,
            cmData.sxUserName,
            cmData.sxContent.PutLineBreaks(),
            cmData.dtmDate.ToString("dd MMM yyyy, HH:mm") // nantinya ini diisi tanggal
            );

        return sxOutput;
    }

    public static String BuildUserEventItem(this UserEventData ueData)
    {
        String sxOutput = String.Format(
            "<div>" +
                "<table cellspacing=\"0\" cellpadding=\"0\" id=\"{1}_{0}\" border=\"0\" class=\"ntT\">" +
                    "<tr>" +
                        "<td valign=\"top\" style=\"width:50px;\">" +
                            "<a href=\"{4}\"><img src=\"upload/{1}.jpg\" alt=\"\" class=\"cmP\" onerror=\"setEmptyUserAvatar(this);\"/></a>" +
                        "</td>" +
                        "<td valign=\"top\" style=\"padding-left:5px;\">" +
                            "<strong>{5}</strong>" +
                            "<br/><a href=\"{4}\">{2} {3}</a>" +
                        "</td>" +
                    "</tr>" +
                "</table>" +
            "</div>",
            NOTIF_DIV_ID,
            ueData.iCompanyId > 0 ?
                "company/" + ueData.iCompanyId.ToString():
                "avatar/" + ueData.sxUserId,
            ueData.sxContent,
            ueData.dtmDate.ToString("dd MMM yyyy, HH:mm"),
            ueData.sxURL,
            ueData.iCompanyId > 0 ?
                ueData.sxCompanyName:
                ueData.sxUserName
            );


        return sxOutput;
    }

    public static String BuildNotificationItem(this NotificationData nfData)
    {
        String sxUsers = String.Empty;

        foreach (String item in nfData.GetUserList())
        {
            sxUsers += String.IsNullOrEmpty(sxUsers) ? String.Empty : ", ";
            
            sxUsers += String.Format("<strong>{0}</strong>", item);
        }

        String sxOutput = String.Format(
            "<div>" +
                "<table cellspacing=\"0\" cellpadding=\"0\" id=\"{1}_{0}\" border=\"0\" class=\"ntT{6}\">" +
                    "<tr>" +
                        "<td valign=\"top\" style=\"width:50px;\">" +
                            "<a href=\"NewsFeed.aspx?mode=profile&uid={2}\"><img src=\"upload/avatar/{2}.jpg\" alt=\"\" class=\"cmP\" onerror=\"setEmptyUserAvatar(this);\"/></a>" +
                        "</td>" +
                        "<td valign=\"top\" style=\"padding-left:5px;\">" +
                            "<a href=\"NewsFeed.aspx?nfid={0}\">{3} {4}</a>" +
                            "<br/>" +
                            "<div class=\"cmD\">{5}</div>" +
                        "</td>" +
                    "</tr>" +
                "</table>" +
            "</div>",
            nfData.NewsFeedID,
            NOTIF_DIV_ID,
            nfData.sxUserId,
            sxUsers,
            nfData.sxContent,
            nfData.dtmDate.ToString("dd MMM yyyy, HH:mm"), // nantinya ini diisi tanggal
            nfData.IsRead ? "_Read" : String.Empty
            );


        return sxOutput;
    }

    public static String BuildCommentForm(int iNewsFeedId, String sxUserId )
    {
        String sxOutput = String.Format(
            "<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\" class=\"cmT\">" +
                "<tr>" +
                    "<td valign=\"top\" style=\"width:50px;\">" +
                        "<a href=\"NewsFeed.aspx?mode=profile&uid={1}\"><img src=\"upload/avatar/{1}.jpg\" alt=\"\" class=\"cmP\" onerror=\"setEmptyUserAvatar(this);\"/></a>" +
                    "</td>" +
                    "<td valign=\"top\" style=\"padding-left:5px;\">" +
                        "<div><textarea id=\"{2}_{0}\" class=\"cmTA\" " + 
                            "onfocus=\"SetFocus(this);\" onblur=\"SetBlur(this);\">tulis komentar...</textarea></div>" +
                        "<input type=\"button\" class=\"btd\" id=\"bt_{0}\" disabled=\"true\" name=\"bt_com\" onclick=\"SendComment(this, '{0}');\" value=\"comment\" />" +
                    "</td>" +
                "</tr>" +
            "</table>",
            iNewsFeedId.ToString(),
            sxUserId,
            COMMENT_TXT_ID);

        return sxOutput;
    }

    public static String BuildCustomerList(String sxUserId, int iPageNumber)
    {
        String sxOutput = String.Empty;
        Cached.CompanyTable ccCompany = new Cached.CompanyTable();

        DataTable dtCompanyList = ccCompany.GetCompanyCarSalesList();

        int iPageSize = KGlobal.DEFAULT_PAGESIZE;

        int iStart = (iPageNumber - 1) * iPageSize;
        int iEnd = ((iPageNumber) * iPageSize) - 1;

        String sxPagerLink = CustomControls.Create_PagerLink(
            "NewsFeed.aspx",
            String.Format("?mode=customer&uid={0}&page", sxUserId),
            iPageNumber,
            dtCompanyList.Rows.Count,
            iPageSize);

        sxOutput += sxPagerLink;

        for (int i = iStart; i <= iEnd; i++)
        {
            if (i >= dtCompanyList.Rows.Count)
                break;

            DataRow dr = dtCompanyList.Rows[i];

            CompanyProfileData cpd = new CompanyProfileData();
            cpd.ID = dr.ReadInt("CUSTOMER_ID");
            cpd.sxCompanyName = dr.ReadString("COMPANY_NAME");
            cpd.sxCAREmployeeNo = dr.ReadString("CAR_EMPLOYEE_NO");
            cpd.sxCARName = dr.ReadString("CAR_NAME");
            cpd.sxSalesEmployeeNo = dr.ReadString("SALES_EMPLOYEE_NO");
            cpd.sxSalesName = dr.ReadString("SALES_NAME");
            sxOutput += cpd.BuildCompanyItem();
        }

        sxOutput += sxPagerLink;

        return sxOutput;
    }

    public static String BuildCustomerList_BySearch(String sxUserId, String sxFilter)
    {
        String sxOutput = String.Empty;
        Cached.CompanyTable ccCompany = new Cached.CompanyTable();

        DataTable dtCompanyList = new DataView(
            ccCompany.GetCompanyOfCarSales(sxUserId),
            String.Format("COMPANY_NAME like '%{0}%'", sxFilter),
            "COMPANY_NAME asc",
            DataViewRowState.CurrentRows).ToTable();

        for (int i = 0; i < dtCompanyList.Rows.Count; i++)
        {
            DataRow dr = dtCompanyList.Rows[i];

            CompanyProfileData cpd = new CompanyProfileData();
            cpd.ID = dr.ReadInt("CUSTOMER_ID");
            cpd.sxCompanyName = dr.ReadString("COMPANY_NAME");
            cpd.sxCAREmployeeNo = dr.ReadString("CAR_EMPLOYEE_NO");
            cpd.sxCARName = dr.ReadString("CAR_NAME");
            cpd.sxSalesEmployeeNo = dr.ReadString("SALES_EMPLOYEE_NO");
            cpd.sxSalesName = dr.ReadString("SALES_NAME");
            sxOutput += cpd.BuildCompanyItem();
        }
        return sxOutput;
    }

}
